package org.squabble.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.tiles2.TilesView;
import org.squabble.domain.Account;
import org.squabble.domain.AccountProperty;
import org.squabble.domain.SystemProperty;
import org.squabble.exception.SiteDisabledException;
import org.squabble.service.SystemService;
import org.squabble.util.SecurityUtil;

public class SquabbleHandlerInterceptor implements HandlerInterceptor {

	@Autowired
	SystemService systemService;

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (modelAndView.getView() instanceof TilesView) {
			Account account = (Account) modelAndView.getModel().get("account");
			if (account != null) {
				Map<String, AccountProperty> props = account
						.getAccountProperties();
				if (props.containsKey("titleDisplay")) {
					if (((Boolean) props.get("titleDisplay").getValue())
							.booleanValue()) {
						// SystemConfig siteName = systemService
						// .getSystemConfig("SYSTEM_SITE_NAME");
						SystemProperty siteName = systemService
								.getSystemProperty("systemSiteName");
						modelAndView.addObject("siteName", siteName.getValue()
								+ " - ");
					}
				}
			} else {
				SystemProperty siteName = systemService
						.getSystemProperty("systemSiteName");
				modelAndView.addObject("siteName", siteName.getValue() + " - ");
			}
		}

	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// SystemConfig enabled =
		// systemService.getSystemConfig("SYSTEM_ENABLED");
		SystemProperty enabled = systemService
				.getSystemProperty("systemEnabled");

		if (!((Boolean) enabled.getValue()).booleanValue()) {
			if (request.getRequestURI().endsWith("login")) {
				return true;
			}
			if (SecurityUtil.userHasAuthority("ROLE_ADMIN")) {
				return true;
			}
			SystemProperty msg = systemService
					.getSystemProperty("systemMaintenanceMessage");

			// SystemConfig msg = systemService
			// .getSystemConfig("SYSTEM_MAINTENANCE_MESSAGE");
			throw new SiteDisabledException(msg.getValue().toString());
		}
		return true;
	}
}
